import datetime
from django.views.decorators.csrf import csrf_exempt
from django.db.utils import IntegrityError
from django.utils import timezone
import hashlib
import json
import logging
from MBlog_backend.custom_response import custom_response
from user.models import user
from user.models import token as token_model
from django.db.models import ObjectDoesNotExist

logger = logging.getLogger("django.request")


# Create your views here.
@csrf_exempt
def register(request):
    from .models import user
    resp = custom_response()
    body = json.loads(request.body)
    account, nickname, password = body.get('account'), body.get('nickname'), body.get('password')

    user_obj = user(account=account, nickname=nickname, password=password)
    try:
        user_obj.save()
    except IntegrityError:
        resp.set_code(1003)
        resp.set_message('用户名重复！')
        return resp.response
    new_token = set_token(user_obj.id, account, password)
    data = {'Oauth-Token': new_token}
    resp.data_update(data)
    return resp.response


def login(request):
    body = json.loads(request.body)
    logger.info(body)
    account, pwd = body.get('account'), body.get('password')
    resp = custom_response()
    obj_user_li = user.objects.filter(account=account)
    if not obj_user_li:
        resp.set_code(1001)
        resp.set_message('用户不存在！')
        return resp.response
    else:
        try:
            obj_user = obj_user_li.get(password=pwd)
        except ObjectDoesNotExist:
            resp.set_code(1002)
            resp.set_message('密码错误')
            return resp.response
    user_id = obj_user.id
    new_token = set_token(user_id, account, pwd)
    obj_user.last_login_time = timezone.now()
    obj_user.save()
    data = {'Oauth-Token': new_token}
    resp.data_update(dict_params=data)
    return resp.response


def logout(request):
    from user.models import token
    from django.db.models import ObjectDoesNotExist
    resp = custom_response()
    user_token = request.headers.get('Oauth-Token')
    try:
        token.objects.get(token=user_token).delete()
    except ObjectDoesNotExist:
        resp.set_code(1005)
        resp.set_message('用户未登录或登录超时！')
    return resp.response


def current(request):
    from user.models import user
    user_token = request.headers.get('Oauth-Token')
    resp = custom_response()
    user_info = user.objects.filter(token__token=user_token).values('id', 'account', 'nickname', 'avatar').first()
    if user_info:
        resp.set_code(0)
        resp.data_update(user_info)
    else:
        # resp.data_update(session_time_out='timeout')
        resp.set_code(1005)
        resp.set_message('未查询到用户或登录超时！')
    response = resp.response
    response["session_time_out"] = "timeout"
    return response


def set_token(user_id, account, pwd) -> str:
    now_time = datetime.datetime.strftime(datetime.datetime.utcnow(), '%Y%m%d%H%M%S')
    new_token = hashlib.md5((str(user_id) + account + pwd + now_time).encode('utf8')).hexdigest()
    try:
        token_obj = token_model.objects.get(user__id=user_id)
        token_obj.token = new_token
        token_obj.save()
    except Exception as e:
        print(e)
        user_obj = user.objects.get(id__exact=user_id)
        token_obj = token_model(token=new_token, user=user_obj)
        token_obj.save()
    return new_token
